Skip to content

fix(ts-sdk): decode base64 data URLs with media-type parameters - #247

Open
rohitsux wants to merge 3 commits into
superlinked:mainfrom
rohitsux:fix/data-url-media-type-params
Open

fix(ts-sdk): decode base64 data URLs with media-type parameters#247
rohitsux wants to merge 3 commits into
superlinked:mainfrom
rohitsux:fix/data-url-media-type-params

Conversation

@rohitsux

@rohitsux rohitsux commented Aug 31, 2026

Copy link
Copy Markdown

Problem

toImageBytes() in packages/sie_ts_sdk/src/images.ts detects base64 data URLs with the regex:

/^data:[^;]+;base64,(.+)$/

This requires the media type segment to contain no ;. Per RFC 2397, though, the media type may carry parameters (e.g. ;charset=utf-8) or be omitted entirely. Data URLs like:

  • data:image/svg+xml;charset=utf-8;base64,...
  • data:;base64,...

don't match this pattern and fall through to the plain base64 branch, which hands the entire data URL string (including the data:...;base64, prefix) to the base64 decoder. That decoder then either throws InvalidCharacterError under atob (browser) or silently produces corrupted bytes under Buffer.from (Node) — neither of which surfaces as a clear "unsupported input" error.

Fix

Match up to the ;base64, marker instead of requiring a ;-free segment:

/^data:[^,]*;base64,(.+)$/

Base64 payloads never contain a comma, so the capture group still correctly isolates just the payload. Behavior for all previously-matching data URLs is unchanged.

Tests

Added two regression tests to packages/sie_ts_sdk/tests/images.test.ts:

  • a data URL whose media type carries a parameter (image/svg+xml;charset=utf-8)
  • a data URL with an omitted media type (data:;base64,...)

Verified locally: fails-before (both new tests throw on the unpatched regex) / passes-after. tests/images.test.ts 17/17; full @superlinked/sie-sdk suite 484/484; biome check clean; tsc --noEmit (typecheck) clean.

Summary by CodeRabbit

  • Bug Fixes

    • Improved image decoding for base64 data URLs with media type parameters, omitted media types, uppercase markers, and percent-encoded payloads.
    • Added clear errors for unsupported non-base64 data URLs and missing payload delimiters.
    • Preserved support for plain base64 strings and empty base64 payloads.
  • Tests

    • Added coverage for varied data URL formats, empty payloads, percent encoding, case variations, and malformed or unsupported inputs.

toImageBytes()'s regex ^data:[^;]+;base64, requires a ;-free media
type, so valid RFC 2397 data URLs with a media-type parameter (e.g.
data:image/svg+xml;charset=utf-8;base64,...) or an omitted media type
(data:;base64,...) don't match and fall through, handing the entire
data URL to the base64 decoder. That decoder then throws
InvalidCharacterError under atob (browser) or silently corrupts bytes
under Buffer.from (Node).

Fix matches up to the ;base64, marker ([^,]*) instead. Base64 payloads
never contain a comma, so the payload is still captured correctly. No
change in behavior for existing inputs.

Added two regression tests covering a media type with a parameter and
an omitted media type.
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 8062a2c0-1878-46a6-98e1-0c210df0d9fd

📥 Commits

Reviewing files that changed from the base of the PR and between 9de9d6c and 970ddda.

📒 Files selected for processing (2)
  • packages/sie_ts_sdk/src/images.ts
  • packages/sie_ts_sdk/tests/images.test.ts

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

Changes

Image data URL decoding

Layer / File(s) Summary
Data URL detection and validation
packages/sie_ts_sdk/src/images.ts, packages/sie_ts_sdk/tests/images.test.ts
toImageBytes now parses case-insensitive base64 data URLs with media-type parameters, omitted media types, empty payloads, and percent-encoded payloads. It throws explicit errors for non-base64 data URLs and missing delimiters. Tests cover successful decoding and these error cases.

Suggested reviewers: dragosboca

Merge Risk: ⚪ Minimal · up to 970dd

Image data URLs now accept valid base64 variations and return clear errors for malformed or non-base64 inputs. The covered behavior is ready to merge with no identified current-head risk.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: fixing TypeScript SDK decoding for base64 data URLs with media-type parameters.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Aug 31, 2026
@mamayer19
mamayer19 requested a review from a team as a code owner September 7, 2026 08:06

@mamayer19 mamayer19 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution, this reproduces the original issue clearly, and both new cases pass locally. I left one suggestion about parsing the data URL structurally instead of broadening the regex, along with a few related edge cases that would make the behavior explicit.

Comment thread packages/sie_ts_sdk/src/images.ts Outdated
// everything up to the ";base64," marker rather than a single ";"-free
// segment — otherwise such URLs fall through and the whole data URL is
// handed to the base64 decoder (corrupting the bytes or throwing).
const dataUrlMatch = input.match(/^data:[^,]*;base64,(.+)$/);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we avoid encoding the data-URL grammar in a regex here? Since the format has a well-defined comma delimiter, a small helper could find the first comma and inspect the semicolon-delimited metadata before it for the final base64 marker. That would be easier to follow and give us a natural place to handle the scheme and marker case-insensitively, percent-decode the payload, and return a clear error for malformed data: input.

As written, inputs such as DATA:image/png;BASE64,SGVsbG8%3D still miss the match and are passed to the raw-base64 decoder. Would you be open to extracting something like parseBase64DataUrl(input): string | undefined, leaving base64ToBytes responsible only for decoding the extracted payload?

it("decodes a data URL whose media type carries a parameter", async () => {
// Valid per RFC 2397: the media type may be followed by ";param=value"
// (e.g. charset) before ";base64,". "Hello" base64-encoded.
const dataUrl = "data:image/svg+xml;charset=utf-8;base64,SGVsbG8=";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two regression cases are a good start. If we switch to a small parser, could we also cover an uppercase scheme/BASE64 marker, percent-escaped padding such as %3D, and one explicit empty-payload case? Those are the boundaries where the current regex falls through into the raw-base64 path, and the tests would make the intended behavior clear.

…ases

Replace the data-URL regex in toImageBytes with a parseBase64DataUrl helper
that walks the RFC 2397 grammar structurally: it splits on the first comma,
matches the data: scheme and the base64 marker case-insensitively,
percent-decodes the payload, and throws a clear error for a malformed or
non-base64 data: URL instead of silently handing it to the base64 decoder.
base64ToBytes is now responsible only for decoding the extracted payload.

Add tests for an uppercase scheme and BASE64 marker, percent-escaped padding
(%3D), an empty payload, and the two clear-error cases.
@rohitsux

rohitsux commented Sep 8, 2026

Copy link
Copy Markdown
Author

Thanks for the review — reworked it along your suggestion.

  • Replaced the regex with parseBase64DataUrl(input): string | undefined that walks the grammar structurally: it finds the first comma, checks the ;-delimited metadata's last segment for the base64 marker, matches the data: scheme and the marker case-insensitively, and percent-decodes the payload. base64ToBytes is now responsible only for decoding the extracted payload.
  • Inputs like DATA:image/png;BASE64,SGVsbG8%3D now parse correctly. A data: URL that's malformed (no comma / bad percent-encoding) or not base64-encoded throws a clear error instead of falling through to the raw decoder; a non-data: string still returns undefined and is treated as raw base64.
  • Added tests for the uppercase scheme/BASE64 marker, percent-escaped %3D padding, an empty payload, and the two error cases.

Full SDK suite is green (513) with typecheck + biome clean. Happy to adjust the error wording if you'd prefer something different.

// base64 string (which can never begin with "data:", since ":" is not a
// base64 character) is decoded as-is.
const payload = parseBase64DataUrl(input);
return base64ToBytes(payload ?? input);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One behavior suggestion: data:;base64, now returns an empty Uint8Array and succeeds. That zero-byte "image" then goes out over the wire as { data: , format: "jpeg" } and fails somewhere in the server, far from the actual mistake. Empty payload should throw too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants